package com.truth.lock.executor.redisson;

import com.truth.lock.enumeration.TruthLockType;
import com.truth.lock.factory.TruthExecutorBeanFactory;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.ExecutionException;

/**
 * @author truth
 * Redisson写锁
 */
public class RedissonWriteLockExecutor implements RedissonLockExecutor {

    private final RedissonClient redissonClient;

    public RedissonWriteLockExecutor(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public RLock acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
        RLock writeLock = redissonClient.getReadWriteLock(lockKey).writeLock();
        boolean locked = lock(writeLock, expire, acquireTimeout);
        return acquireLockInstance(locked, writeLock);
    }

    @Override
    public boolean releaseLock(String key, String value, RLock lockInstance) {
        if (lockInstance.isHeldByCurrentThread()) {
            try {
                return lockInstance.forceUnlockAsync().get();
            } catch (ExecutionException | InterruptedException exception) {
                return false;
            }
        }
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        TruthExecutorBeanFactory.register(TruthLockType.REDISSON_WRITE_LOCK, this);
    }
}
